package com.yuedou.api.commons.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "CorsFilter ")
@Configuration
public class CorsFilter implements Filter {

    final static Logger logger = LoggerFactory.getLogger(CorsFilter.class);

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, Authorization");
//        System.out.println("*********************************过滤器被使用**************************");
        HttpServletRequest request = (HttpServletRequest) req;
        String accessToken = request.getHeader("access_token");
        String userId = request.getHeader("user_id");
        String address = request.getRemoteAddr();
//        if(userId.equals("817")){
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("application/json; charset=utf-8");
//            PrintWriter writer = response.getWriter();
//            writer.write(Tools.getJson(new GsonResultBean<>(2, "非法访问！"), true, true).toString());
//            System.out.println("非法访问： accessToken： " + accessToken + ", " + DateUtil.getTime() + "------ 请求的IP地址： " + address);
//        }
//        XssHttpServletRequestWrapper xssHttpServletRequestWrapper=new XssHttpServletRequestWrapper(request);
//        chain.doFilter(xssHttpServletRequestWrapper, response);

        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {
        System.out.println("init=========================");
    }
    public void destroy() {}
}
